/**
 * 
 */
package org.dse.analysis;

/**
 * This class is created for the data structure in the segmenter. The segmenter
 * is a full-segmenter when indexing, so it must compare the tokens according to
 * their positions for returning. The class implements the Comparable interface
 * and the logic of comparing.
 * 
 * @author zhangchen
 * 
 */
@SuppressWarnings("unchecked")
public class TokenDelegate implements Comparable {

	private int offset;
	private int begin;
	private int end;
	private Token token;

	/**
	 * The constructor.
	 * 
	 * @param offset
	 *            the read offset
	 * @param begin
	 *            the begin index from the offset
	 * @param end
	 *            the end index from the offset
	 */
	TokenDelegate(int offset, int begin, int end) {
		this.offset = offset;
		this.begin = begin;
		this.end = end;
	}

	/**
	 * Fill its wrapped token.
	 * 
	 * @param term
	 *            the word content
	 */
	public void setTerm(String term) {
		token = new Token(term, offset + begin);
	}

	/**
	 * equals.
	 * 
	 * @param o
	 *            another object to be compared
	 * @return a boolean value to show whether they are equal
	 */
	public boolean equals(Object o) {
		if (o instanceof TokenDelegate) {
			TokenDelegate ntd = (TokenDelegate) o;
			if (begin == ntd.getBegin() && end == ntd.getEnd())
				return true;
		}
		return false;
	}

	/**
	 * Return its hashcode.
	 * 
	 * @return an integer representing its hashcode
	 */
	public int hashCode() {
		return begin * 17 + end * 23;
	}

	/**
	 * compareTo.
	 * 
	 * @param o
	 *            another object to be compared
	 * @return an integer representing the compare result
	 */
	public int compareTo(Object o) {
		TokenDelegate ntd = (TokenDelegate) o;
		if (begin < ntd.begin)
			return -1;
		if (begin == ntd.begin) {
			if (end > ntd.end)
				return -1;
			if (end == ntd.end)
				return 0;
			if (end < ntd.end)
				return 1;
		}
		return 1;
	}

	/**
	 * Get begin index.
	 * 
	 * @return the begin index
	 */
	public int getBegin() {
		return begin;
	}

	/**
	 * Get end index.
	 * 
	 * @return the end index
	 */
	public int getEnd() {
		return end;
	}

	/**
	 * Get the token.
	 * 
	 * @return the token
	 */
	public Token getToken() {
		return token;
	}

	/**
	 * Get the offset.
	 * 
	 * @return the offset
	 */
	public int getOffset() {
		return offset;
	}
}